<template>
	<el-tag class="tag" v-for="tag in linkType" :key="tag.id" closable :disable-transitions="false" @close="handleClose(tag.id)" @click="tagClick(tag)">
		<el-input v-if="updateId == tag.id" v-model="updateValue" style="width: 100px;" size="small" @keyup.enter="updateConfirm" @blur="updateConfirm" />
		<span v-else>{{ tag.name }}</span>
	</el-tag>
	<!-- </el-popconfirm> -->
	<el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" style="width: 100px;" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
	<el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">+ New Tag</el-button>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, nextTick } from 'vue';
import { ElInput } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useMainStore } from '@/store/index.js';
import { storeToRefs } from 'pinia';
const { proxy } = getCurrentInstance();
// 链接类型的新增 ⬇⬇⬇⬇
const inputValue = ref('');
const updateValue = ref('');
const updateId = ref('');
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

//引入piana
const mainStore = useMainStore();
const { linkType } = storeToRefs(mainStore);
mainStore.getLinkType();

//删除类型
const handleClose = (tag: string) => {
	console.log(tag);
	ElMessageBox.confirm('是否确认删除该课程?', '警告!!', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			proxy
				.$post('/link/type/delete', {
					id: tag
				})
				.then(res => {
					console.log(res);
					if (res.code === 200) {
						mainStore.getLinkType();
					} else {
						ElMessage({
							type: 'error',
							message: res.msg
						});
					}
				});
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除'
			});
		});
};
//准备新增类型
const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value!.input!.focus();
	});
};
//确定新增类型
const handleInputConfirm = () => {
	if (inputValue.value) {
		console.log(6666);
		proxy
			.$post('/link/type/add', {
				name: inputValue.value
			})
			.then(res => {
				console.log(res);
				if (res.code === 200) {
					mainStore.getLinkType();
				}
			});
	}
	inputVisible.value = false;
	inputValue.value = '';
};
const tagClick = tag => {
	console.log(tag);
	updateId.value = tag.id;
	updateValue.value = tag.name;
};
//确定修改
const updateConfirm = () => {
	if (updateValue.value) {
		console.log(6666);
		let params = { name: updateValue.value, id: updateId.value };
		console.log(params);
		proxy.$post('/link/type/update', params).then(res => {
			console.log(res);
			if (res.code === 200) {
				mainStore.getLinkType();
			}
		});
	}
	updateId.value = '';
	updateValue.value = '';
};
// 链接类型的新增 以上 ⬆⬆⬆⬆
</script>

<style lang="less" scoped>
.type {
	& > * {
		margin: 5px;
	}
}
</style>
